<template>
  <div class="dashboard-home">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <h1>欢迎使用文档管理系统</h1>
        <p>在这里您可以方便地管理和分享您的文档</p>
      </div>
    </div>

    <!-- 文件上传区域 -->
    <div class="upload-box">
      <h2>上传文档</h2>
      <el-upload
        class="upload-area"
        drag
        :action="`${API_BASE_URL}/documents/`"
        :headers="uploadHeaders"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        multiple
      >
        <div class="upload-content">
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处或 <em>点击上传</em>
          </div>
        </div>
      </el-upload>
      <div class="upload-tip">
        支持上传 DOC, DOCX, PDF, XLS, XLSX, PPT, PPTX 等格式文件
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="stat-header">
            <el-icon><Document /></el-icon>
            <span>文档总数</span>
          </div>
        </template>
        <div class="stat-content">
          <div class="stat-value">{{ stats.totalDocuments }}</div>
          <div class="stat-label">个文档</div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="stat-header">
            <el-icon><Download /></el-icon>
            <span>总下载次数</span>
          </div>
        </template>
        <div class="stat-content">
          <div class="stat-value">{{ stats.totalDownloads }}</div>
          <div class="stat-label">次下载</div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="stat-header">
            <el-icon><Files /></el-icon>
            <span>文件总大小</span>
          </div>
        </template>
        <div class="stat-content">
          <div class="stat-value">{{ stats.totalSize }}</div>
          <div class="stat-label">存储空间</div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="stat-header">
            <el-icon><Histogram /></el-icon>
            <span>文件类型分布</span>
          </div>
        </template>
        <div class="stat-content">
          <div class="stat-value">{{ stats.fileTypes || 0 }}</div>
          <div class="stat-label">种类型</div>
        </div>
      </el-card>
    </div>

    <el-row :gutter="20">
      <el-col :span="16">
        <!-- 文件类型分布图表 -->
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>文件类型分布</span>
              <el-radio-group v-model="chartType" size="small">
                <el-radio-button value="pie">饼图</el-radio-button>
                <el-radio-button value="bar">柱状图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="chartRef"></div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <!-- 快捷操作 -->
        <el-card class="quick-actions" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>
          <div class="actions-list">
            <el-button type="primary" @click="$router.push('/dashboard/documents')">
              <el-icon><Document /></el-icon>查看文档
            </el-button>
            <el-button type="info" @click="$router.push('/dashboard/profile')">
              <el-icon><User /></el-icon>个人资料
            </el-button>
          </div>
        </el-card>

        <!-- 最近活动 -->
        <el-card class="recent-activity" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近活动</span>
              <el-button link type="primary" @click="fetchActivities">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="activity in recentActivities"
              :key="activity.id"
              :timestamp="activity.time"
              :type="activity.type"
              size="large"
            >
              <div class="activity-content">
                {{ activity.content }}
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>

    <!-- 上传列表 -->
    <el-card class="upload-list" v-if="uploadedFiles.length > 0">
      <template #header>
        <div class="card-header">
          <h3>已上传文件</h3>
        </div>
      </template>
      
      <el-table :data="uploadedFiles" style="width: 100%">
        <el-table-column prop="title" label="文件名" />
        <el-table-column prop="file_type" label="类型" width="100" />
        <el-table-column prop="file_size_formatted" label="大小" width="100" />
        <el-table-column prop="upload_time" label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.upload_time) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button link type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, onUnmounted } from 'vue'
import { Document, Download, Files, Upload, User, Histogram, Refresh } from '@element-plus/icons-vue'
import axios from '../utils/axios'  // 使用自定义的axios实例
import * as echarts from 'echarts'
import { ElMessage, ElMessageBox } from 'element-plus'

const API_BASE_URL = 'http://localhost:8000/api'
const chartRef = ref(null)
const chartType = ref('pie')
let chart = null

const stats = ref({
  totalDocuments: 0,
  totalDownloads: 0,
  totalSize: '0 B',
  fileTypes: 0
})

const recentActivities = ref([
  {
    id: 1,
    content: '上传了新文档 "项目计划书.docx"',
    time: '2024-03-09 14:30',
    type: 'primary'
  },
  {
    id: 2,
    content: '下载了文档 "会议记录.pdf"',
    time: '2024-03-09 13:15',
    type: 'success'
  },
  {
    id: 3,
    content: '删除了文档 "旧版文档.doc"',
    time: '2024-03-09 11:20',
    type: 'danger'
  }
])

// 修改上传相关的计算属性
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('access_token')
  return {
    'Authorization': token ? `Bearer ${token}` : ''
  }
})

const uploadedFiles = ref([])

const fetchStats = async () => {
  try {
    const response = await axios.get('/documents/')  // 使用相对路径
    const documents = response.data
    const fileTypes = new Set(documents.map(doc => doc.file_type)).size

    stats.value = {
      totalDocuments: documents.length,
      totalDownloads: documents.reduce((sum, doc) => sum + doc.download_count, 0),
      totalSize: formatFileSize(documents.reduce((sum, doc) => sum + doc.file_size, 0)),
      fileTypes: fileTypes
    }

    // 更新图表数据
    updateChart(documents)
  } catch (error) {
    console.error('Error fetching stats:', error)
    if (error.response?.status === 401) {
      ElMessage.error('请先登录')
    }
  }
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const updateChart = (documents) => {
  if (!chartRef.value) return

  // 如果图表实例不存在，创建新的实例
  if (!chart) {
    chart = echarts.init(chartRef.value)
  }

  // 统计文件类型分布
  const typeCount = {}
  documents.forEach(doc => {
    typeCount[doc.file_type] = (typeCount[doc.file_type] || 0) + 1
  })

  // 准备图表数据
  const data = Object.entries(typeCount).map(([name, value]) => ({ name, value }))

  // 根据图表类型设置不同的配置
  const options = {
    title: {
      text: '文件类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle'
    }
  }

  if (chartType.value === 'pie') {
    options.series = [{
      type: 'pie',
      radius: '50%',
      data: data,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  } else {
    options.xAxis = {
      type: 'category',
      data: data.map(item => item.name)
    }
    options.yAxis = {
      type: 'value'
    }
    options.series = [{
      type: 'bar',
      data: data.map(item => item.value)
    }]
  }

  // 设置图表配置
  chart.setOption(options)
}

// 监听图表类型变化
watch(chartType, () => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  fetchStats()
})

// 监听窗口大小变化
window.addEventListener('resize', () => {
  if (chart) {
    chart.resize()
  }
})

const fetchActivities = () => {
  // 这里可以添加获取最近活动的API调用
  // 现在使用模拟数据
}

// 修改上传成功处理函数
const handleUploadSuccess = (response, file) => {
  ElMessage.success(`文件 ${file.name} 上传成功`)
  fetchUploadedFiles()
  fetchStats()
}

// 修改上传失败处理函数
const handleUploadError = (error, file) => {
  console.error('Upload error:', error)
  ElMessage.error(`文件 ${file.name} 上传失败: ${error.response?.data?.detail || '未知错误'}`)
}

// 修改上传前的验证函数
const beforeUpload = (file) => {
  const allowedTypes = [
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/pdf',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'text/plain'
  ]
  
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error(`不支持的文件类型: ${file.type}`)
    return false
  }

  // 检查文件大小（例如限制为1GB）
  const maxSize = 1 * 1024 * 1024 * 1024 // 1GB
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过1GB')
    return false
  }

  return true
}

const fetchUploadedFiles = async () => {
  try {
    const response = await axios.get('/documents/')  // 使用相对路径
    uploadedFiles.value = response.data
  } catch (error) {
    console.error('Error fetching documents:', error)
    if (error.response?.status === 401) {
      ElMessage.error('请先登录')
    }
  }
}

const handleDelete = (file) => {
  ElMessageBox.confirm(
    '确定要删除这个文件吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await axios.delete(`/documents/${file.id}/`)  // 使用相对路径
      ElMessage.success('删除成功')
      fetchUploadedFiles()
      fetchStats()
    } catch (error) {
      console.error('Delete error:', error)
      ElMessage.error(error.response?.data?.detail || '删除失败')
    }
  }).catch(() => {})
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchStats()
  fetchUploadedFiles() // 添加获取上传文件列表
  window.addEventListener('resize', () => {
    chart && chart.resize()
  })
})

// 组件卸载时清理图表实例
onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.dashboard-home {
  max-width: 1200px;
  margin: 0 auto;
}

.welcome-section {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border-radius: 8px;
  padding: 30px;
  margin-bottom: 30px;
  color: white;
  text-align: center;
}

.welcome-section h1 {
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: 500;
}

.welcome-section p {
  font-size: 16px;
  opacity: 0.9;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.stat-content {
  text-align: center;
  padding: 10px 0;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.chart-card {
  margin-bottom: 20px;
  height: 400px;
}

.chart-container {
  height: 320px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.quick-actions {
  margin-bottom: 20px;
}

.actions-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.actions-list .el-button {
  justify-content: flex-start;
  padding: 12px;
}

.actions-list .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.recent-activity {
  margin-bottom: 20px;
}

.el-timeline {
  padding: 20px;
  max-height: 300px;
  overflow-y: auto;
}

.activity-content {
  color: #606266;
  font-size: 14px;
}

.upload-box {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  text-align: center;
  border: 1px dashed #dcdfe6;
}

.upload-box h2 {
  font-size: 16px;
  color: #606266;
  margin-bottom: 20px;
  font-weight: normal;
}

.upload-area {
  width: 100%;
}

.upload-content {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.el-upload {
  width: 100%;
  height: 180px;
}

.el-upload-dragger {
  width: 100%;
  height: 180px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  background-color: #fff;
}

.el-upload-dragger:hover {
  border-color: #409EFF;
}

.el-icon--upload {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.el-upload__text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.el-upload__text em {
  color: #409EFF;
  font-style: normal;
  cursor: pointer;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
  text-align: center;
}

.upload-list {
  margin-top: 20px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .stat-cards {
    grid-template-columns: 1fr;
  }
  
  .el-col {
    width: 100% !important;
  }
  
  .chart-card {
    height: 300px;
  }
  
  .chart-container {
    height: 220px;
  }

  .upload-section {
    margin: 20px 0;
  }
  
  .el-table {
    width: 100%;
    overflow-x: auto;
  }
}
</style> 